<?php
// +----------------------------------------------------------------------
// | 双擎基础框架 [ 基于ThinkLibrary扩展 ]
// +----------------------------------------------------------------------
// | 感谢ThinkLibrary原作者Anyon的封装
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://www.sqm.la All rights reserved.
// +----------------------------------------------------------------------
// | Author: rotoos <87291030@qq.com>
// +----------------------------------------------------------------------
namespace think\admin\service;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Ses\V20201002\Models\SendEmailRequest;
use TencentCloud\Ses\V20201002\SesClient;
use think\admin\Exception;
use think\admin\model\SysEmail;
use think\admin\Service;

/**
 * 腾讯云邮件发送服务
 * @class TencentEmailService
 * @package think\admin\service
 */
class TencentEmailService extends Service
{
    /**
     * Secret ID
     * @var string
     */
    protected string $secretId;

    /**
     * Secret Key
     * @var string
     */
    protected string $secretKey;

    /**
     * Region Id
     * @var string
     */
    protected string $regionId;

    /**
     * 发送单个邮件
     * @param $to
     * @param string $sendAccount
     * @param string $sendUser
     * @param string $subject
     * @param string $content
     * @param bool $isHtml
     * @return bool
     */
    public function singleSendMail(
        $to,
        string $sendAccount = '',
        string $sendUser = '',
        string $subject = '',
        string $content = '',
        bool $isHtml = false
    ): bool {
        try {
            $cred = new Credential($this->secretId, $this->secretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("ses.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SesClient($cred, $this->regionId, $clientProfile);

            $params = [
                "FromEmailAddress" => $sendUser . '<' . $sendAccount . '>',
                "Destination" => $to,
                "Simple" => [
                    "Html" => $isHtml ? $content : '',
                    "Text" => !$isHtml ? $content : ''
                ],
                "Subject" => $subject
            ];

            $req = new SendEmailRequest();
            $req->fromJsonString(json_encode($params));
            $resp = $client->SendEmail($req);

            $state = false;
            $dat = [
                'engine' => 'TENCENT',
                'send_account' => $sendAccount,
                'send_user' => $sendUser,
                'receive_accounts' => $to,
                'subject' => $subject,
                'content' => $content
            ];

            if ($resp->toJsonString()) {
                $state = true;
                $dat['receipt_info'] = json_encode($resp->toJsonString());
            }

            SysEmail::mk()->insert($dat);

            return $state;
        } catch (TencentCloudSDKException $e) {
            // Log the error or handle it as per requirement
            return false;
        }
    }

    /**
     * 批量发送模板邮件
     * @param array $to
     * @param string $sendAccount
     * @param string $subject
     * @param string $templateName
     * @param string $templateParam
     * @return bool
     */
    public function batchSendEmail(
        array $to,
        string $sendAccount = '',
        string $subject = '',
        string $templateName = '',
        string $templateParam = ''
    ): bool {
        try {
            $cred = new Credential($this->secretId, $this->secretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("ses.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SesClient($cred, $this->regionId, $clientProfile);

            $params = [
                "FromEmailAddress" => $sendAccount,
                "Destination" => $to,
                "Template" => [
                    "TemplateID" => $templateName,
                    "TemplateData" => $templateParam
                ],
                "Subject" => $subject
            ];

            $req = new SendEmailRequest();
            $req->fromJsonString(json_encode($params));
            $resp = $client->SendEmail($req);

            $state = false;
            $dat = [
                'engine' => 'TENCENT',
                'send_account' => $sendAccount,
                'receive_accounts' => $to,
                'subject' => $subject,
                'template_name' => $templateName,
                'template_param' => $templateParam
            ];

            if ($resp->toJsonString()) {
                $state = true;
                $dat['receipt_info'] = json_encode($resp->toJsonString());
            }

            SysEmail::mk()->insert($dat);

            return $state;
        } catch (TencentCloudSDKException $e) {
            // Log the error or handle it as per requirement
            return false;
        }
    }

    /**
     * 控制器初始化
     * @return void
     * @throws Exception
     */
    protected function initialize(): void
    {
        $config = sysconfig('EMAIL_TENCENT');
        $this->secretId = $config['SQM_EMAIL_TENCENT_SECRET_ID'] ?? '';
        $this->secretKey = $config['SQM_EMAIL_TENCENT_SECRET_KEY'] ?? '';
        $this->regionId = $config['SQM_EMAIL_TENCENT_REGION_ID'] ?? '';
    }
}
